package com.wpre.vampiremq.mqserver.datacenter;

import com.wpre.vampiremq.mqserver.core.Binding;
import com.wpre.vampiremq.mqserver.core.Exchange;
import com.wpre.vampiremq.mqserver.core.MSGQueue;
import com.wpre.vampiremq.mqserver.core.Message;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description: 这个类用来管理所有的硬盘上的数据:
 * 1.数据库:交换机,绑定,队列
 * 2.数据文件:消息
 * 上层逻辑通过这个类来进行硬盘操作
 * User: LianBao
 * Date: 2025-01-15
 * Time: 20:44
 */
public class DiskDataCenter {

    //管理数据库中的数据
    private DataBaseManager dataBaseManager = new DataBaseManager();

    //管理数据文件中的数据
    private MessageFileManager messageFileManager = new MessageFileManager();

    //初始化工作
    public void init() {
        dataBaseManager.init();
        messageFileManager.init();
    }

    //封装交换机操作
    //插入交换机
    public void insertExchange(Exchange exchange) {
        dataBaseManager.insertExchange(exchange);
    }
    //删除交换机
    public void deleteExchange(String exName) {
        dataBaseManager.deleteExchange(exName);
    }
    //查询所有交换机
    public List<Exchange> selectAllExchanges() {
        return dataBaseManager.selectAllExchanges();
    }

    //封装队列操作
    //插入队列
    public void insertQueue(MSGQueue queue) throws IOException {
        //插入队列的同时,也要创建对应的队列目录
        messageFileManager.createQueueFiles(queue.getName());
        dataBaseManager.insertQueue(queue);
    }
    //删除队列
    public void deleteQueue(String queueName) throws IOException {
        //删除队列的同时,也要删除对应的队列目录
        dataBaseManager.deleteQueue(queueName);
        messageFileManager.deleteQueueFile(queueName);
    }
    //查询所有队列
    public List<MSGQueue> selectAllQueues() {
        return dataBaseManager.selectAllQueues();
    }

    //封装绑定操作
    //插入绑定
    public void insertBinding(Binding binding) {
        dataBaseManager.insertBinding(binding);
    }
    //删除绑定
    public void deleteBinding(Binding binding) {
        dataBaseManager.deleteBinding(binding);
    }
    //查询所有绑定
    public List<Binding> selectAllBindings() {
        return dataBaseManager.selectAllBindings();
    }

    //封装消息操作
    //发送消息
    public void sendMessage(MSGQueue queue, Message message) throws IOException {
        messageFileManager.sendMessage(queue, message);
    }
    //删除消息
    public void deleteMessage(MSGQueue queue, Message message) throws IOException, ClassNotFoundException {
        messageFileManager.deleteMessage(queue, message);
        if (messageFileManager.checkGC(queue.getName())) {
            messageFileManager.GC(queue);
        }
    }
    //加载消息
    public LinkedList<Message> loadAllMessageFromQueue(String queueName) throws IOException, ClassNotFoundException {
        return messageFileManager.loadAllMessageFromQueue(queueName);
    }


}
